// src/stores/user.ts
import { defineStore } from 'pinia';
import { login, logout, getUserInfo } from '@/api/user';
import { resetRouter } from '@/router/resetRouter';

export const useUserStore = defineStore('user', {
    state: () => ({
        token: localStorage.getItem('token') || '',
        userInfo: null as UserInfo | null,
        roles: [] as string[],
        isRoutesAdded: false
    }),
    getters: {
        isLoggedIn: state => !!state.token,
        userName: state => state.userInfo?.name || '',
        avatar: state => state.userInfo?.avatar || ''
    },
    actions: {
        // 登录
        async login(loginForm: LoginParams) {
            try {
                const res = await login(loginForm);
                if (res.code === 200) {
                    this.token = res.data.token;
                    localStorage.setItem('token', res.data.token);
                    return true;
                }
                return false;
            } catch (error) {
                console.error('登录失败', error);
                return false;
            }
        },

        // 获取用户信息
        async getUserInfo() {
            try {
                const res = await getUserInfo();
                if (res.code === 200) {
                    this.userInfo = res.data;
                    this.roles = res.data.roles || ['user'];
                    return res.data;
                }
                return null;
            } catch (error) {
                console.error('获取用户信息失败', error);
                throw error;
            }
        },

        // 退出登录
        async logout() {
            try {
                await logout();
            } catch (error) {
                console.error('退出登录失败', error);
            } finally {
                this.resetToken();
                resetRouter();
            }
        },

        // 重置Token
        resetToken() {
            this.token = '';
            this.userInfo = null;
            this.roles = [];
            this.isRoutesAdded = false;
            localStorage.removeItem('token');
        },

        // 设置路由已添加状态
        setRoutesAdded(status: boolean) {
            this.isRoutesAdded = status;
        }
    }
});